from socket import *
import sys

def get_file_content(file_name):
    try:
        with open(file_name, "rb") as f:
            content = f.read()
        return content
    except:
        print("没有下载的文件:%s" % file_name)


def main():
    if len(sys.argv) != 2:
        print("请按照如下方式运行：python3 xxx.py 7890")
        return
    else:
        port = int(sys.argv[1])


    tcp_server_socket = socket(AF_INET, SOCK_STREAM)
    address = ('', port)
    tcp_server_socket.bind(address)
    tcp_server_socket.listen(128)

    while True:
        client_socket, clientAddr = tcp_server_socket.accept()
        recv_data = client_socket.recv(1024)
        file_name = recv_data.decode("utf-8")
        print("对方请求下载的文件名为:%s" % file_name)
        file_content = get_file_content(file_name)
        if file_content:
            client_socket.send(file_content)
        client_socket.close()

    tcp_server_socket.close()


if __name__ == "__main__":
    main()